﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Microsoft.SharePoint;
using PS.Config.Samples;
using PS.Config.Utils;

namespace PS.Config
{
    public class Controller
    {
        public Controller()
        {
            Links = new Links();
            Email = new Email();
            Sections = new object[] { Links, Email };
        }

        public Email Email { get; set; }
        public Links Links { get; set; }

        private static Controller _instance;
        public readonly object[] Sections;
        private static bool _initialized;

        public static Controller Current
        {
            get
            {
                EnsureInitialized();
                return _instance;
            }
        }

        private static void EnsureInitialized()
        {
            lock (typeof(Controller))
            {
                if (!_initialized)
                {
                    Init();
                    _initialized = true;
                }
            }
        }
        public static void Init(SPWeb web)
        {
            PropertyBagHelper.ProvidedWeb = web;
            Init();
        }
        public static void Init()
        {
//            if (SPContext.Current == null)
//            {
//                return;
                //When run under powershell, SPContext.Current will be null and the custom config section may not exist => create new un-initialized object w/ default values
//                _instance = XmlSection<Controller>.GetSection("LocConfig") ?? new Controller();
//            }
//            else
//            {
                _instance = new Controller();
                InitFromPropertyBag(_instance.Sections);
//            }
        }

        private static void InitFromPropertyBag(IEnumerable objects)
        {
            if (objects == null)
                throw new ArgumentNullException("objects", @"Objects property missing");

            foreach (var obj in objects)
            {
                var fields = ReflectionHelper.EnumFields(obj);
                foreach (var pair in fields)
                {
                    var value = pair.Key.GetPropertyBagValue();
                    if (!string.IsNullOrEmpty(value))
                        pair.Value.SetValue(obj, value, null);
                }
            }
        }




    }


}
